package com.willpower.vueshop.controller;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @project: spring-security-oauth2-demo;
 * @package: com.wen.springsecurityoauth2demo.config.controller;
 * @author: Administrator;
 * @date: 2021/8/30 23:42;
 * @Description: 资源
 */
@RestController
@RequestMapping("/user")
@PreAuthorize("hasRole('ROLE_root')")
public class UserController {

    // 返回资源
    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication){
        //当使用Jwt令牌获取时 只能获取用户名 所以直接改成authentication
        return authentication;
    }

    //Jwt令牌获取资源
    @RequestMapping("/getJwtCurrentUser")
    public Object getJwtCurrentUser(Authentication authentication, HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        String token = authorization.substring(authorization.indexOf("Bearer") + 7);
        SecretKey key = Keys.hmacShaKeyFor("caAihCz53DZRjWtbsGcZJ2Ai6At+T142uphtJMsk7iQ=".getBytes(StandardCharsets.UTF_8));
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
    }
}
